<?php

namespace App\Http\Controllers\Web;

use App\Models\News;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use function PHPUnit\Framework\isEmpty;

class NewsController extends Controller
{
    public function index(Request $request)
    {

        $size = $request->input('size', 10);
        $query = News::query();

        $title = $request->input("title");
        $type = $request->input("type");
        $author = $request->input("author");
        $publish_date_start = $request->input("publish_date_start");
        $publish_date_end = $request->input("publish_date_start");
        $query->when($title, function ($query) use ($title) {
            $query->where('title', "like", "%{$title}%");
        });
        if ($type || $type === '0') {
            $query->where('type', $type);
        }
        $query->when($author, function ($query) use ($author) {
            $query->where('author', "like", "%{$author}%");
        });
        $query->when($publish_date_start, function ($query) use ($publish_date_start) {
            $query->where('publish_date', ">=", $publish_date_start);
        });
        $query->when($publish_date_end, function ($query) use ($publish_date_end) {
            $query->where('publish_date', "<=", $publish_date_end);
        });

        return $this->successPaginate($query->paginate($size));
    }

    public function requestData(Request $request)
    {
        $requestData = $this->validate($request, [
            'title' => 'required',
            'content' => 'required',
            'author' => "required",
            'publish_date' => 'required',
            "type" => 'required',
            "cover_url" => 'required',
            "abstract" => 'nullable',
            "tags" => 'nullable',
            'title_en' => 'nullable',
            'content_en' => 'nullable',
            'author_en' => "nullable",
            "cover_url_en" => 'nullable',
            "abstract_en" => 'nullable',
            "tags_en" => 'nullable'
        ]);
        return $requestData;
    }

    public function show($id)
    {
        $new = News::query()->findOrFail($id);
        return $this->success($new);
    }

    public function store(Request $request)
    {
        $new = new News;
        $requestData = $this->requestData($request);
        $new->fill($requestData);
        $new->save();
        return $this->success($requestData);
    }

    public function update(Request $request, $id)
    {
        $new = News::query()->findOrFail($id);
        $requestData = $this->requestData($request);
        $new->fill($requestData);
        $new->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $new = News::query()->findOrFail($id);
        $new->delete();
    }
}
